#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <functional>
#include <unordered_map>
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <cstdarg>
#include <cstdio>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>


const int maxListen = 1024;       // backlog,listen全队列最大数量
const int maxEpollEvents = 1024;  // 存储revents的最大数量
const uint64_t defaultBufferSize = 1024;  // buff缓冲区默认初始化大小

// 日志等级
#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4
// 日志输出方式
#define Screan 1
#define Onefile 2
#define Classfile 3
// 日志文件名
#define LOGFILE "log.txt"  

#define LOG(level, format, ...) lg(level, __FILE__, __LINE__, format, ##__VA_ARGS__)

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    LOG是一个实现简易日志打印的类
*/
class Log
{
    const int SIZE = 1024;
private:
    int _printMethod;   // 打印日志的方式
    std::string _path;  // 日志保存的路径

private:
    /*············································

                将日志等级转化为字符串
    
    ············································*/
    std::string levelToString(int level)
    {
        switch (level)
        {
            case Info:    return "Info";
            case Debug:   return "Debug";
            case Warning:  return "Warning";
            case Error:    return "Error";
            case Fatal:    return "Fatal";
            default:      return "None";
        }
    }
    /*············································

                    打印日志
    
    ············································*/
    void printLog(int level, const std::string& logtxt)
    {
        switch (_printMethod)
        {
            case Screan:     std::cout << logtxt << std::endl;  break;
            case Onefile:    printOnefile(LOGFILE, logtxt);  break;
            case Classfile:  printClassfile(level, logtxt);  break;
            default: break;
        }
    }
    /*············································

                以单个文件输出的方式打印日志 
    
    ············································*/
    void printOnefile(const std::string& logname, const std::string& logtxt)
    {   
        char cwd[SIZE];
        getcwd(cwd, sizeof(cwd));
        // 检测存放logtxt的路径是否为当前工作目录
        if (_path != "./" && _path != std::string(cwd))
        {
            mkdir(_path.c_str(),0777);
        }
        std::string filename = _path + logname;
        int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
        if (fd < 0)
        {
            perror("openLogfile fail, errno string");
            return;
        }
        write(fd, logtxt.c_str(), logtxt.size());
        const char newline = '\n';
        write(fd, &newline, sizeof(char));
        close(fd);
    }
    /*············································

            以多个文件分类的方式打印日志    
    
    ············································*/
    void printClassfile(int level, const std::string& logtxt)
    {
        std::string filename = LOGFILE;
        filename += "." + levelToString(level);
        printOnefile(filename, logtxt);
    }

public:
    Log(int _outmethod = Screan)
        :_printMethod(_outmethod) ,_path("./log/")
    {}
    /*············································

                设置日志的输出方式     
    
    ············································*/
    void outMethod(int method)
    {
        _printMethod = method;
    }
    /*············································

                    打印日志 
    
    ············································*/
    void operator()(int level, const char* file, const int line, const char* format, ...)
    {
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t);
        char leftbuffer[SIZE];
        snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d] [%s:%d]", levelToString(level).c_str(),
                ctime->tm_year+1900, ctime->tm_mon+1, ctime->tm_mday,
                ctime->tm_hour, ctime->tm_min, ctime->tm_sec,
                file, line);
        
        va_list s;
        va_start(s, format);
        char rightbuffer[SIZE];
        vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
        va_end(s);

        char logtxt[SIZE*2];
        snprintf(logtxt, sizeof(logtxt), "%s %s", leftbuffer, rightbuffer);
        
        printLog(level, logtxt);
    }
    ~Log()
    {}
};

Log lg;

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Buffer模块是一个缓冲区模块,用于实现通信用户中用户态的接收缓冲区和发送缓冲区功能

*/
class Buffer
{
private:
    uint64_t _reader_idx;       // 读偏移量
    uint64_t _writer_idx;       // 写偏移量
    std::vector<char> _buffer;  // 使用vector进行内存空间管理
public:
    Buffer(const uint64_t bufferSize = defaultBufferSize) :_reader_idx(0), _writer_idx(0), _buffer(bufferSize) 
    {}
// 以下private接口供public接口使用
private:
    /*············································

                获取vector元素的首地址
    
    ············································*/
    char* Begin() 
    { 
        return &(*_buffer.begin()); 
    }
    /*············································

       获取缓冲区末尾空闲空间大小,size - 写偏移量
    
    ············································*/
    const uint64_t TailFreeSize() 
    { 
        return _buffer.size() - _writer_idx; 
    }
    /*············································

       获取缓冲区头部空闲空间大小,size - 读偏移量
    
    ············································*/
    const uint64_t HeadFreeSize() 
    { 
        return  _reader_idx; 
    }
    /*············································

            容量检查,确保可写空间足够
    
    ············································*/
    void EnsureWirteSpace(const uint64_t len)
    {
        // 如果末尾空闲大小足够,则直接返回
        if (len <= TailFreeSize()) { return; }
        // 如果末尾空闲大小不够,则加上头部空闲大小,如果足够,则将读的数据前移
        if (len <= TailFreeSize() + HeadFreeSize()) {
            // 将读的数据移动到起始地址
            uint64_t readSize = ReadAbleSize();
            std::copy(ReadPosition(), ReadPosition() + readSize, Begin());  // 将数据拷贝到起始地址 
            _reader_idx = 0;
            _writer_idx = readSize;
        }
        else {  // 所有空闲大小不够,需要扩容
            _buffer.resize((_writer_idx + len) * 1.5);
        }
    }
    /*············································

                    写入数据
    
    ············································*/
    void _Write(const void* data, const uint64_t len)
    {
        // 1.确保有足够的空间
        if (len == 0) { return; }
        EnsureWirteSpace(len);
        // 2.拷贝数据
        std::copy((const char*)data, (const char*)data + len, WritePostion());
        MoveWriteOffset(len);
    }
    /*············································

                    读取数据
    
    ············································*/
    void _Read(void* buffer, const uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::copy(ReadPosition(), ReadPosition() + len, (char*)buffer);
        MoveReadOffset(len);
    }
    /*············································

                    寻找换行符
    
    ············································*/
    char* FindCRLF()
    {
        char* res = (char*)memchr(ReadPosition(), '\n', ReadAbleSize());
        return res;
    }
// 暴露的接口,供用户使用
public:
    /*············································

    获取当前写入的起始地址,_buffer元素起始地址+写偏移量
    
    ············································*/
    char* WritePostion() 
    { 
        return Begin() + _writer_idx; 
    }
    /*············································

    获取当前读取的起始地址,_buffer元素起始地址+读偏移量
    
    ············································*/
    char* ReadPosition() 
    { 
        return Begin() + _reader_idx; 
    }
    /*············································

                将读偏移变量向后移动
    
    ············································*/
    void MoveReadOffset(const uint64_t len)
    {
        if (len == 0) { return; }
        // 向后移动的大小,必须小于可读数据大小
        assert(len <= ReadAbleSize());
        _reader_idx += len;
    }
    /*············································

                将写偏移变量向后移动
    
    ············································*/
    void MoveWriteOffset(const uint64_t len)
    {
        if (len == 0) { return; }
        assert(len <= TailFreeSize());
        _writer_idx += len;
    }
    /*············································

       获取可读数据大小,写偏移量-读偏移量
    
    ············································*/
    const uint64_t ReadAbleSize() 
    { 
        return _writer_idx - _reader_idx;
    }
    /*············································

                    写入数据
    
    ············································*/
    void Write(const void* data, const uint64_t len)
    {
        _Write(data, len);
    }
    void WriteString(const std::string& data)
    {
        _Write(data.c_str(), data.size());
    }
    void WriteBuffer(Buffer& data)
    {
        _Write(data.ReadPosition(), data.ReadAbleSize());
    }
    /*············································

                    读取数据
    
    ············································*/
    void Read(void* buffer, const uint64_t len)
    {
        _Read(buffer, len);
    }
    std::string ReadString(const uint64_t len)
    {
        // 要求获取的数据大小必须小于等于可读数据大小
        assert(len <= ReadAbleSize());
        std::string str;
        str.resize(len);
        // 由于c_str()返回的是const,因此传入&str[0]
        _Read(&str[0], len);
        return str;
    }
    /*············································

                    清空缓冲区
    
    ············································*/
    void Clear()
    {
        _reader_idx = 0;
        _writer_idx = 0;
    }
    /*············································

           获取一行数据,针对的是明文数据的情况
    
    ············································*/   
    std::string GetLine()
    {
        // 寻找换行符
        char* pos = FindCRLF();
        if (pos == NULL) { return ""; }
        return ReadString(pos - ReadPosition() + 1);
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Socket模块是对套接字操作封装的一个模块,主要实现socket的各项操作

*/
class Socket
{
private:
    int _sockfd;
public:
    Socket(): _sockfd(-1)
    {}
    Socket(const int fd): _sockfd(fd)  // 用于管理Accept新连接上来的clientfd
    {}
    ~Socket() { Close(); }
    /*············································

              获取套接字文件描述符sockfd
    
    ············································*/   
    const int GetFd() 
    { 
        return _sockfd; 
    }
    /*············································

                    创建套接字
    
    ············································*/   
    bool CreateSocket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  // _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0) {
            LOG(Error, "Create Socket err, strerr: %s : %d", strerror(errno), errno);
            return false;
        }
        LOG(Info, "CreateSocket success, sockfd: %d", _sockfd);
        return true;
    }
    /*············································

                    绑定地址信息
    
    ············································*/   
    bool Bind(const std::string& ip, const uint64_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        //addr.sin_addr.s_addr = inet_addr(ip.c_str());
        inet_pton(AF_INET, ip.c_str(), &(addr.sin_addr));
        socklen_t len = sizeof(addr);
        int ret = bind(_sockfd, (struct sockaddr*)&addr, len);
        if (ret < 0) {
            LOG(Error, "Bind err, strerr: %s : %d", strerror(errno), errno);
            return false;
        }
        LOG(Info, "Bind success, sockfd: %d ip: %s : %d", _sockfd, ip.c_str(), port);
        return true;
    }
    /*············································

                监听sock套接字
    
    ············································*/   
    bool Listen(const int backlog = maxListen)
    {
        int ret = listen(_sockfd, backlog);
        if (ret < 0) {
            LOG(Error, "Listen err, strerr: %s : %d", strerror(errno), errno);
            return false;
        }
        LOG(Info, "Listen success, sockfd: %d, backlog: %d", _sockfd, backlog);
        return true;
    }
    /*············································

                获取客户端的新链接
    
    ············································*/   
    const int Accept()
    {
        int newfd = accept(_sockfd, NULL, NULL);
        if (newfd < 0) {
            LOG(Warning, "Accept err, strerr: %s : %d", strerror(errno), errno);
            return -1;
        }
        LOG(Info, "Accept success, clientfd: %d", newfd);
        return newfd;
    }
    /*············································

                向服务端发起连接
    
    ············································*/   
    bool Connect(const std::string& ip, uint16_t port)
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(server.sin_addr));
        socklen_t len = sizeof(server);
        int ret = connect(_sockfd, (struct sockaddr*)&server, len);
        if (ret < 0) {
            LOG(Warning, "Connect err, strerr: %s : %d", strerror(errno), errno);
            return false;
        }
        LOG(Info, "Connection server success, svr_ip: %s : %d", ip.c_str(), port);
        return true;
    }
    /*············································

                    接收数据
    
    ············································*/   
    const ssize_t Recv(void* buf, size_t len, int flags = 0)
    {
        ssize_t ret = recv(_sockfd, buf, len, flags);
        if (ret <= 0) {
            // EAGAIN 当前socket的接收缓冲区中没有数据了,在非阻塞的情况下才会有这个错误
            // EINTR 表示当前socket的阻塞等待,被信号打断了
            if (errno == EAGAIN | EINTR) { return 0; }  // 表示这次接收 没有接收到数据
            // 连接断开和出错都返回-1
            LOG(Warning, "Recv Err, strerr: %s : %d", strerror(errno), errno);
            return -1;
        }
        return ret;
    }
    /*············································

                    非阻塞Recv
    
    ············································*/
    const ssize_t NonBlockRecv(void *buf, size_t len)
    {
        return Recv(buf, len, MSG_DONTWAIT);  // MSG_DONTWAIT表示当前接收为非阻塞
    }       
    /*············································

                    发送数据
    
    ············································*/   
    const ssize_t Send(const void* buf, size_t len, int flags = 0)
    {
        ssize_t ret = send(_sockfd, buf, len, flags);
        if (ret <= 0) {
            // EAGAIN 当前socket的接收缓冲区中没有数据了,在非阻塞的情况下才会有这个错误
            // EINTR 表示当前socket的阻塞等待,被信号打断了
            if (errno == EAGAIN | errno == EINTR) { return 0; }
            // 连接断开和出错都返回-1
            LOG(Warning, "Send err, strerr: %s : %d", strerror(errno), errno);
            return -1;
        }
        return ret;
    }
    /*············································

                    非阻塞Send
    
    ············································*/ 
    const ssize_t NonBlockSend(const void* buf, size_t len)
    {
        return Send(buf, len, MSG_DONTWAIT);  // MSG_DONTWAIT表示当前发送为非阻塞
    }  
    /*············································

                    关闭套接字
    
    ············································*/   
    void Close()
    {
        if (_sockfd != -1) {
            close(_sockfd);
            LOG(Info, "Close sockfd: %d", _sockfd);
            _sockfd = -1;
        }
    }
    /*············································

                    创建一个服务端
    
    ············································*/
    bool CreateServer(const uint16_t port, const std::string& ip = "0.0.0.0", bool block_flag = false)
    {
        // 创建套接字
        if (CreateSocket() == false) { return false; }
        // 设置sockfd是否非阻塞
        if (block_flag == true) { NonBlock(); }
        // 设置地址端口复用
        ReuseAddress();
        // 绑定地址
        if (Bind(ip, port) == false) { return false; }
        // 监听sockfd
        if (Listen() == false) { return false; }
        return true;
    }
    /*············································

                    向服务端发起链接
    
    ············································*/  
    bool CreateClient(const uint16_t port, const std::string& ip)
    {
        // 创建套接字
        if (CreateSocket() == false) { return false; }
        // 向服务器发起链接
        if (Connect(ip, port) == false) { return false; }
        return true;
    }
    /*············································

                设置sockfd为非阻塞
    
    ············································*/
    void NonBlock()
    {
        int flag = fcntl(_sockfd, F_GETFL, 0);
        fcntl(_sockfd, F_SETFL, flag | O_NONBLOCK);
    }
    /*············································

                设置地址端口复用
    
    ············································*/
    void ReuseAddress()
    {
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        LOG(Info, "ReuseAddress enable!");
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Channel模块是对一个描述符需要进行的IO事件管理的模块,实现对描述符可读,可写,错误...事件的管理操作,
    以及Poller模块对描述符进行IO事件监控就绪后,根据不同的事件,回调不同的处理函数的功能

*/
class Epoller;
class EventLoop;
class Channel
{
    using EventCallback = std::function<void()>;
private:
    int _fd;            // 监控的文件描述符
    EventLoop* _loop;
    uint32_t _events;   // 监控的事件
    uint32_t _revents;  // 哪些事件就绪的结果 

    EventCallback _read_callback;         // 读就绪事件回调函数
    EventCallback _write_callback;        // 写就绪事件回调函数
    EventCallback _error_callback;        // 错误就绪事件回调函数
    EventCallback _close_callback;        // 断开就绪事件回调函数
    EventCallback _any_events_callback;   // 任意就绪事件回调函数
public:
    Channel(EventLoop* Loop, const int fd) :_fd(fd), _loop(Loop), _events(0), _revents(0)
    {}
    /*············································

                获取文件描述符
    
    ············································*/
    const int GetFd()
    {
        return _fd;
    }
    /*············································

                获取需要监控的就绪事件
    
    ············································*/
    uint32_t GetEvents()
    {
        return _events;
    }
    /*············································

               设置就绪事件的结果           
    
    ············································*/
    void SetRevents(const uint32_t events)
    {
        _revents = events;
    }
    /*············································

                设置事件就绪的回调函数
    
    ············································*/
    void SetReadCallback(const EventCallback& cb)
    {
        _read_callback = cb;
    }
    void SetWriteCallback(const EventCallback& cb)
    {
        _write_callback = cb;
    }
    void SetErrorCallback(const EventCallback& cb)
    {
        _error_callback = cb;
    }
    void SetCloseCallback(const EventCallback& cb)
    {
        _close_callback = cb;
    }
    void SetAnyEventsCallback(const EventCallback& cb)
    {
        _any_events_callback = cb;
    }
    /*············································

                是否监控读事件就绪
    
    ············································*/
    bool ReadAble()
    {
        return (_events & EPOLLIN);
    }
    /*············································

                是否监控写事件就绪
    
    ············································*/
    bool WriteAble()
    {
        return (_events & EPOLLOUT);
    }
    /*············································

                设置监控读事件就绪
    
    ············································*/
    void EnableRead()
    {
        _events |= EPOLLIN;
        Update(); 
    }
    /*············································

                设置监控写事件就绪
    
    ············································*/
    void EnableWrite()
    {
        _events |= EPOLLOUT;
        Update();
    }
    /*············································

                关闭读事件就绪的监控
    
    ············································*/
    void DisableRead()
    {
        _events &= ~EPOLLIN;
        Update();
    }
    /*············································

                关闭写事件就绪的监控
    
    ············································*/
    void DisableWrite()
    {
        _events &= ~EPOLLOUT;
        Update();
    }
    /*············································

                关闭所有事件就绪的监控
    
    ············································*/
    void DisableEvents()
    {
        _events = 0;
        Update();
    }
    /*············································

                    移除监控
    由于只声明了类Epoller,而其函数声明在此类后面,
    因此只能在Epoller后面实现,此处只做Remove()的声明

    ············································*/
    void Remove();
    /*············································

          更新监控的events,events改动时执行这个
    由于只声明了类Epoller,而其函数声明在此类后面,
    因此只能在Epoller后面实现,此处只做Update()的声明

    ············································*/
    void Update();
    /*············································

    事件处理,一旦出发了事件,则调用这个函数来派发任务
    
    ············································*/
    void Dispatcher()
    {
        // 读事件就绪 or 读关闭 or 读优先, 调用读就绪事件回调函数
        if ((_revents & EPOLLIN) || (_revents & EPOLLRDHUP) || (_revents & EPOLLPRI)) {
            if (_read_callback) { _read_callback(); }
        }
        // 有可能会释放链接的操作事件,一次只处理一个,
        if (_revents & EPOLLOUT) {
            if (_write_callback) { _write_callback(); }
        }
        else if (_revents & EPOLLERR) {
            if (_error_callback) { _error_callback(); }
        }
        else if (_revents & EPOLLHUP) {
            if (_close_callback) { _close_callback(); }
        }
        if (_any_events_callback) { _any_events_callback(); }
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Poller模块是对epoll进行操作封装的一个模块,主要实现epoll的各项操作
    实现epoll的IO事件添加,修改和移除,获取活跃链接功能

*/
class Epoller
{   
private:
    int _epfd;      // epoll的描述符
    struct epoll_event _evs[maxEpollEvents];      // 存储revents
    std::unordered_map<int, Channel*> _channels;  // 存储文件描述符与channel的值键对
// 以下private接口供public接口使用
private:
    /*············································

                    对epoll进行操作
    
    ············································*/
    void Update(Channel* channel, int op)
    {
        int fd = channel->GetFd();
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = channel->GetEvents();
        int ret = epoll_ctl(_epfd, op, fd, &ev);
        if (ret < 0) {
            LOG(Warning, "Update epoll_cttl err, strerr: %s : %d", strerror(errno), errno);
            return ;
        }
    }
    /*············································

            判断一个channel是否添加了事件监控
    
    ············································*/
    bool HashChannel(Channel* channel)
    {
        auto it = _channels.find(channel->GetFd());
        if (it == _channels.end()) { return false; }
        return true;
    }
// 暴露的接口,接口供用户使用
public:
    Epoller()
    {
        _epfd = epoll_create(1024);
        if (_epfd < 0) {
            LOG(Fatal, "Epoll Create err, strerr: %s : %d", strerror(errno), errno);
            abort();  // 退出程序
        }
        LOG(Info, "Epoll create success, _epfd: %d", _epfd);
    }
    /*············································

                  添加,修改监控事件
    
    ············································*/
    void UpdateEvent(Channel* channel)
    {
        bool ret = HashChannel(channel);
        if (ret == false) {
            // 不存在则添加到hash里
            _channels.insert(std::make_pair(channel->GetFd(), channel));
            return (Update(channel, EPOLL_CTL_ADD));
        }
        return (Update(channel, EPOLL_CTL_MOD));
    }
    /*············································

                    移除监控事件
    
    ············································*/
    void RemoveEvent(Channel* channel)
    {
        auto it = _channels.find(channel->GetFd());
        if (it != _channels.end()) {
            _channels.erase(it);
        }
        Update(channel, EPOLL_CTL_DEL);
    }
    /*············································

                    获取活跃链接
    
    ············································*/
    void Epoll(std::vector<Channel*> *active)
    {
        int nfds = -1;
        while (1) {
            nfds =  epoll_wait(_epfd, _evs, maxEpollEvents, -1);
            if (nfds < 0) {
                // 被信号异常打断,等待下次接收
                if (errno == EINTR || errno == EAGAIN) { continue; }  
                // epoll_wait 出错
                LOG(Error, "Poll epoll_wait err, strerr: %s : %d", strerror(errno), errno);
                abort();  // 退出程序
            }
            // 成功获取到就绪事件,跳出循环
            break;
        }
        for (int i = 0; i < nfds; ++i) {
            auto it = _channels.find(_evs[i].data.fd);
            assert(it != _channels.end());
            // 设置revents的结果给对应的channel
            it->second->SetRevents(_evs[i].events);
            active->push_back(it->second);
        }
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    TimerTask是一个用来存储任务信息的类
    TimerWheel是一个时间轮的类,用来管理并轮询执行TimerTask

*/

class TimerTask
{
    using TaskFunc = std::function<void()>;
    using ReleaseFunc = std::function<void()>;
private:
    uint64_t _id;             // 定时器任务对象ID
    uint32_t _delay;        // 定时任务的超时时间
    bool _canceled;           // false-->没有被取消; true-->被取消
    TaskFunc _task_cb;        // 定时器对象要执行的定时任务
    ReleaseFunc _release_cb;  // 用于删除TimerWheel中保存的定时器对象信息

public:
    TimerTask(const uint64_t id, const uint32_t delay, const TaskFunc& task_cb)
        :_id(id), _delay(delay), _canceled(false), _task_cb(task_cb)
        {}
    ~TimerTask()
    {
        if (_canceled == false) { _task_cb(); }
        _release_cb();
    }
    void Cancel()
    {
        _canceled = true;
    }
    void SetRelease(const ReleaseFunc& release_cb)
    {
        _release_cb = release_cb;
    }
    uint32_t DelayTime()
    {
        return _delay;
    }
};
class EventLoop;
class TimerWheel
{
    using TaskFunc = std::function<void()>;
    using ReleaseFunc = std::function<void()>;
    // PtrTask用shared_ptr,刷新定时任务,因引用计数的存在,所以前面已存在的不用管
    // 再根据WeakTask来获取对应的shared_ptr,push到_wheel[(_tick + delay) % _capacity]
    using PtrTask = std::shared_ptr<TimerTask>; 
    using WeakTask = std::weak_ptr<TimerTask>;
private:
    int _tick;  // 当前的秒针,走到哪里释放到哪里,释放就相当于执行任务
    int _capacity;  // 表盘最大数量--->最大延迟时间
    std::vector<std::vector<PtrTask>> _wheel; 
    std::unordered_map<uint64_t, WeakTask> _timers;  // 记录任务ID和TimerTask*的值键对

    EventLoop* _loop;
    int _timerfd;  // 定时器描述符 --- 可读事件回调就是读取计数器,执行定时任务
    std::unique_ptr<Channel> _timer_channel;  // 管理定时器描述符的监控事件
// 以下private接口供public接口使用
private:
    /*············································

                移除_timers中的TimerTask

    ············································*/
    void RemoveTimer(uint64_t id)
    {
        auto it = _timers.find(id);
        if (it != _timers.end()) { _timers.erase(it); }
        else {
            LOG(Warning, "RemoveTImer err, not find Timer: %d", id);
            return;
        }
    }
    /*············································

                创建一个定时器timerfd

    ············································*/
    static int CreateTimerFd()
    {
        // itn timerfd_create(int clockid, int flags);
        // clockid:  CLOCK_REALTIME: 系统时间  CLOCK_MONOTONIC: 相较于开机的时间  一般采用相较于开机时间
        // flags:  0-->默认阻塞属性
        int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
        if (timerfd < 0)
        {
            LOG(Error, "CreateTimerFd err, strerr: %s : %d", strerror(errno), errno);
            abort();
        }
        struct itimerspec itime;
        itime.it_value.tv_sec = 1;      // 第一次超时时间为1s
        itime.it_value.tv_nsec = 0;
        itime.it_interval.tv_sec = 1;   // 第一次超时后,每次超时的时间间隔为1s
        itime.it_interval.tv_nsec = 0;  

        timerfd_settime(timerfd, 0, &itime, NULL);
        // flags: 0-->相对时间, 1-->绝对时间
        return timerfd;
    }

    /*············································

                获取已超时时间次数

    ············································*/
    int ReadTimeFd()
    {
        uint64_t times;
        // 有可能因为其他描述符的事件处理花费事件比较长,然后在处理定时器描述符事件的时候,有可能就已经超时了很多次
        // read读取到的数据times就是从上一次read之后超时的次数
        int ret = read(_timerfd, &times, sizeof(times));
        if (ret < 0) {
            LOG(Error, "ReadTimeFd read err, strerr: %s : %d", strerror(errno), errno);
            abort();
        }
        return times;
    }
    /*············································

    _tick指针轮询,应每秒钟被执行一次,相当于秒针向后走一步

    ············································*/
    void RunTimerTask()
    {
        _tick = (_tick + 1) % _capacity;
        _wheel[_tick].clear();
    }
    /*············································

        根据ReadTimeFd()获取timerfd超时次数
        根据实际超时次数执行对应的超时任务

    ············································*/     
    void OnTime()
    {
        int times = ReadTimeFd();
        for (int i = 0; i < times; ++i) {
            RunTimerTask();
        }
    }
    /*············································

                    添加定时任务

    ············································*/
    void TimerAddInLoop(uint64_t id, uint32_t delay, const TaskFunc& cb)
    {
        PtrTask pt = std::make_shared<TimerTask>(id, delay, cb);
        pt->SetRelease(std::bind(&TimerWheel::RemoveTimer, this, id));
        int pos = (_tick + delay) % _capacity;
        _wheel[pos].push_back(pt);
        _timers[id] = WeakTask(pt);
    }
    /*············································

                    刷新定时任务

    ············································*/
    void TimerRefreshInLoop(uint64_t id)
    {
        // 通过保存的定时器对象的weak_ptr构造一个shared_ptr出来,添加到时间轮中
        auto it = _timers.find(id);
        if (it == _timers.end()) {
            LOG(Warning, "TimerRefresh err, not find Timer: %d", id);
            return;
        }
        if (PtrTask pt = it->second.lock()) {  // lock获取weak_ptr管理的对象对应的shared_ptr
            int delay = pt->DelayTime();
            int pos = (_tick + delay) % _capacity;
            _wheel[pos].push_back(pt);
        }
        else {
            LOG(Warning, "TimerRefresh err, weak_ptr is null!");
            return;
        }
    }
    /*············································

                    取消定时任务

    ············································*/
    void TimerCancelInLoop(uint64_t id)
    {
        auto it = _timers.find(id);
        if (it == _timers.end()) {
            LOG(Info, "TimerCancel err, not find Timer: %d", id);
            return;
        }

        if (PtrTask pt = it->second.lock()) { pt->Cancel(); }
        else {
            LOG(Warning, "TimerCancel err, weak_ptr is null!");
            return;
        }
    }
public:
    TimerWheel(EventLoop* loop): _tick(0), _capacity(60), _wheel(_capacity),
                  _loop(loop), _timerfd(CreateTimerFd()),
                  _timer_channel(new Channel(_loop, _timerfd))
    {
        _timer_channel->SetReadCallback(std::bind(&TimerWheel::OnTime, this));
        _timer_channel->EnableRead();
    }
    /*············································

    定时器中有个_timers成员,定时器信息的操作有可能在多线程中进行
    因此需要考虑线程安全问题
    如果不想加锁,那就把对定时器的所有操作都放在一个线程中进行
    以下函数因涉及调用EventLoop内,因此在EventLoop的定义后面实现

    ············································*/  
    void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc& cb);  // _loop->RunInLoop(std::bind(&TimerWheel:TimerAddInLoop, this, id))
    void TimerRefresh(uint64_t id);  // _loop->RunInLoop(std::bind(&TimerWheel:TimerRefreshInLoop, this, id))
    void TimerCancel(uint64_t id);   // _loop->RunInLoop(std::bind(&TimerWheel:TimerCancelInLoop, this, id))
    /*············································

                判断Hash中是否存在id
    这个接口存在线程安全问题--这个接口实际上不能被外界使用者调用
    只能在模块内，在对应的EventLoop线程内执行

    ············································*/
    bool HasTimer(uint64_t id) {
        auto it = _timers.find(id);
        if (it == _timers.end()) { return false; }
        return true;
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    EventLoop模块可以理解就是Reactor模块,它是对Epoller模块,TimerQueue模块，
    Socket模块的⼀个整体封装，进⾏所有描述符的事件监控。

*/
class EventLoop
{
    using TaskFunc = std::function<void()>;
    using ReleaseFunc = std::function<void()>;
    using Functor = std::function<void()>;
private:
    int _event_fd;      // eventfd唤醒IO事件监控(epoll_wait)有可能导致的阻塞
    Epoller _epoll;     // 进行所有描述符的事件监控
    std::mutex _mutex;  // 实现任务池操作的线程安全锁
    TimerWheel _timer_wheel;      // 定时器模块
    std::thread::id _thread_id;   // 线程id
    std::vector<Functor> _tasks;  // 任务池
    std::unique_ptr<Channel> _event_channel;  // 用于eventfd的事件管理的channel
// 以下private接口供public接口使用
private:
    /*············································

                创建一个eventfd

    ············································*/
    static int CreateEventFd()
    {
        // EFD_CLOEXEC: 不可被进程复制  EFD_NONBLOCK: 非阻塞
        int efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
        if (efd < 0) {
            LOG(Error, "CreateEventFd eventfd err, strerr: %s : %d", strerror(errno), errno);
            abort();
        }
        LOG(Info, "CreateEventFd success!");
        return efd;
    }
    /*············································

            eventfd可读事件的回调函数
    
    ············································*/
    void ReadEventFd()
    {
        uint64_t res = 0;
        int ret = read(_event_fd, &res, sizeof(res));
        if (ret < 0) {
            // EINTR -- 被信号打断  EAGAIN -- 表示无数据可读
            if (errno == EINTR || errno == EAGAIN) { return; }
            LOG(Error, "ReadEventFd read err, strerr: %s : %d", strerror(errno), errno);
            abort();
        }
    }
    /*············································

            向event_fd写入,用于唤醒IO事件监控
            即epoll_wait有可能导致的阻塞
    
    ············································*/
    void WeakUpEventFd()
    {
        uint64_t val = 1;
        int ret = write(_event_fd, &val, sizeof(val));
            if (ret < 0) {
            // EINTR -- 被信号打断  EAGAIN -- 表示无数据可读
            if (errno == EINTR || errno == EAGAIN) { return; }
            LOG(Error, "WeakUpEventFd write err, strerr: %s : %d", strerror(errno), errno);
            abort();
        }
    }
    /*············································

                执行任务池中的任务
    
    ············································*/
    void RunAllTask()
    {
        std::vector<Functor> functor;
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            _tasks.swap(functor);
        }
        for (auto& f : functor) 
        {
            f();
        }
    }
public:
    EventLoop() :_event_fd(CreateEventFd()), _thread_id(std::this_thread::get_id()),
                _event_channel(new Channel(this, _event_fd)), _timer_wheel(this)
    {
        // 给event_fd添加可读事件回调函数,读取eventfd事件通知次数
        _event_channel->SetReadCallback(std::bind(&EventLoop::ReadEventFd, this));
        // 启动eventfd的读事件监控
        _event_channel->EnableRead();
    }
    /*············································

          事件监控>-->就绪事件处理>-->执行任务
    
    ············································*/
    void Start()
    {
        while(1) {
            // 1. 事件监控
            std::vector<Channel*> actives;
            _epoll.Epoll(&actives);
            // 2. 事件处理
            for (auto& channel : actives) {
                channel->Dispatcher();
            }
            // 3. 执行任务
            RunAllTask();
        }
    }
    /*············································

        判断当前钱财是否是EventLoop对应的线程
    
    ············································*/
    bool IsInLoop()
    {
        return (_thread_id == std::this_thread::get_id());
    }
    void AssertInLoop()
    {
        assert(_thread_id == std::this_thread::get_id());
    }
    /*············································

        判断将要执行的任务是否处于当前线程中
        如果是则运行,不是则压入任务池中
    
    ············································*/
    void RunInLoop(const Functor& cb)
    {
        if (IsInLoop()){ return cb(); }
        return QueueInLoop(cb);
    }
    /*············································

               将操作压入任务池中
    
    ············································*/
    void QueueInLoop(const Functor& cb)
    {
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _tasks.push_back(cb);
        }
        // 唤醒有可能因为没有事件就绪,而导致的epoll阻塞
        // 其实就是给eventfd写入一个数据,eventfd就会触发可读事件
        WeakUpEventFd();
    }
    /*············································

               添加,修改描述符的事件监控
    
    ············································*/
    void UpdateEvent(Channel *channel)
    {
        _epoll.UpdateEvent(channel);
    }
    /*············································

                移除描述符的事件监控
    
    ············································*/
    void RemoveEvent(Channel* channel)
    {
        _epoll.RemoveEvent(channel);
    }
    /*············································

                添加定时任务
    
    ············································*/
    void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc& cb)
    {
        _timer_wheel.TimerAdd(id, delay, cb);
    }
    /*············································

                刷新定时任务
    
    ············································*/
    void TimerRefresh(uint64_t id)
    {
        _timer_wheel.TimerRefresh(id);
    }
    /*············································

                取消定时任务
    
    ············································*/
    void TimerCancel(uint64_t id)
    {
        _timer_wheel.TimerCancel(id);
    }
    /*············································

                判断定时任务是否存在
    
    ············································*/
    bool HashTimer(uint64_t id)
    {
        return _timer_wheel.HasTimer(id);
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

        子线程EventLoop,用于主从Reactor模型的子Reactor
        子Reactor用于处理Accept上来的客户端链接

*/
class LoopThread
{
private:
    // 用于实现_loop获取的同步关系,避免线程创建了但是_loop还没有实例化之前去获取_loop
    std::mutex _mutex; // 用于EventLoop* 的锁
    std::condition_variable _cond;  // 条件变量
    EventLoop* _loop;    // EventLoop指针变量,这个对象需要在线程内实例化
    std::thread _thread; // EventLoop对应的线程
private:
    /*············································

            线程入口函数,用于创建实例化EventLoop对象
            唤醒_cond上有可能阻塞的线程
            并且开始运行EventLoop模块的功能        
    
    ············································*/
    void ThreadEntry()
    {
        EventLoop loop;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _loop = &loop;
            _cond.notify_all();
        }
        loop.Start();
    }
public:
    LoopThread() :_loop(NULL), _thread(std::thread(&LoopThread::ThreadEntry, this))
    {}
    /*············································

            获取当前线程关联的EventLoop对象指针    
    
    ············································*/
    EventLoop* GetLoop()
    {
        EventLoop* loop = NULL;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond.wait(lock, [&](){ return _loop != NULL; }); // _loop为NULL就一直阻塞
            loop = _loop;
        }
        return loop;
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

        EventLoop线程池,即⼦Reactor线程池

*/
class LoopThreadPool
{
private:
    int _thread_count;  // 子Reactor线程数量,即LoopThread数量
    int _next_idx;      // 下一个LoopThread的下标
    EventLoop* _base_loop;  // 主Reactor,即主EventLoop
    std::vector<LoopThread*> _threads;  // 存储子Reactor的LoopThread*
    std::vector<EventLoop*> _loops;     // 存储子Reactor的EventLoop*
public:
    LoopThreadPool(EventLoop* base_loop) :_thread_count(0), _next_idx(0), _base_loop(base_loop)
    {}
    void SetThreadCount(const int count) 
    {
        _thread_count = count;
    }
    void Create()
    {
        if (_thread_count > 0) {
            _threads.resize(_thread_count);
            _loops.resize(_thread_count);
            for (int i = 0; i < _thread_count; ++i) 
            {
                _threads[i] = new LoopThread();
                _loops[i] = _threads[i]->GetLoop();
            }
        }
        LOG(Info, "Create LoopThreadPool success, ThreadCount: %d", _thread_count);
    }
    EventLoop* NextLoop()
    {
        if (_thread_count == 0) { return _base_loop; }
        _next_idx = (_next_idx + 1) % _thread_count;
        return _loops[_next_idx];
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

        通⽤类型any类型

*/
class Any
{
    class holder
    {
    public:
        virtual ~holder() {}
        virtual const std::type_info &type() = 0;
        virtual holder *clone() = 0; 
    };
    template<class T>
    class placeholder: public holder
    {
    public:
        T _val;
    public:
        placeholder(const T &val): _val(val) 
        {}
        /*············································

                    获取子类对象保存的数据类型
        
        ············································*/
        virtual const std::type_info &type() 
        {   
            return typeid(T); 
        }
        /*············································

            针对当前的对象自身,克隆出一个新的子类对象
    
        ············································*/
        virtual holder *clone() 
        { 
            return new placeholder(_val); 
        } 
    };
    
private:
    holder *_content;

public:
    Any() :_content(NULL) 
    {}
    template<class T>
    Any(const T &val) :_content(new placeholder<T>(val)) 
    {}
    Any(const Any &other) :_content(other._content ? other._content->clone() : NULL) 
    {}
    ~Any() 
    { 
        delete _content; 
    }
    /*············································

                交换两个Any对象

    ············································*/
    Any &swap(Any &other)
    {
        std::swap(_content, other._content);
        return *this;
    }
    /*············································

             返回子类对象保存的数据的指针   
    
    ············································*/
    template<class T>
    T* get()
    {
        // 想要获取的数据类型,必须和保存得数据类型一致
        assert(typeid(T) == _content->type());
        return &((placeholder<T>*)_content)->_val;
    }
    /*············································

                赋值运算符的重载函数
    
    ············································*/
    template<class T>
    Any &operator=(const T &val)
    {
        // 为val构造一个临时的通用容器,然后与当前容器自身进行指针交换,临时对象释放的时候,原先保存的数据也就被释放
        Any(val).swap(*this);
        return *this;
    }
    Any &operator=(const Any &other)
    {
        Any(other).swap(*this);
        return *this;
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Connection模块是对Buffer模块,Socket模块,Channel模块的⼀个整体封装,实现了对⼀个通信套
    接字的整体的管理,每⼀个进⾏数据通信的套接字(也就是accept获取到的新连接)都会使⽤
    Connection进⾏管理

*/
// DISCONNECTED -- 连接关闭状态;   CONNECTING -- 连接建立成功,待处理状态
// CONNECTED  -- 连接建立完成,各种设置已完成,可以通信的状态;   DISCONNECTING -- 连接待关闭状态
typedef enum { DISCONNECTED, CONNECTING, CONNECTED, DISCONNECTING} ConnStatu;
class Connection: public std::enable_shared_from_this<Connection>
{
    using PtrConnection = std::shared_ptr<Connection>;
    using ConnectedCallback = std::function<void(const PtrConnection&)>;
    using MessageCallback = std::function<void(const PtrConnection&, Buffer*)>;
    using ClosedCallback = std::function<void(const PtrConnection&)>;
    using AnyEventsCallback = std::function<void(const PtrConnection&)>;
private:
    EventLoop* _loop;    // 连接所关联地一个EventLoop
    uint64_t _conn_id;   // 连接的唯一id,便于连接的管理和查找
//  uint64_t timer_id;   // 定时器的唯一id,为了简化,使用conn_id作为定时器id
    int _sockfd;         // 连接关联的文件描述符
    bool _enable_inactive_release;  // 连接是否启用非活跃销毁的标志,默认为false
    ConnStatu _statu;    // 连接状态
    Socket _socket;      // 套接字操作管理
    Channel _channel;    // 连接的事件管理
    Buffer _in_buffer;   // 输入缓冲区 --- 存放从socket中读取到的数据
    Buffer _out_buffer;  // 输出缓冲区 --- 存放要发送给对端的数据
    Any _context;        // 请求的接受处理上下文

    // 阶段性处理函数,这几个回调都是组件使用者使用的
    ConnectedCallback _connected_callback;  // 连接阶段的回调函数
    MessageCallback _message_callback;      // 处理消息阶段的回调函数
    // 组件内的连接关闭回调 -- 组件内设置的,因为服务器组件内会把所有的连接管理起来
    // 一旦某个连接要关闭,就应该从管理的地方移除掉自己的信息
    ClosedCallback _closed_callback;        // 关闭阶段的回调函数
    AnyEventsCallback _any_events_callback;   // 任意阶段的回调函数

    // 组件内的连接关闭回调--组件内设置的,因为服务器组件内会把所有的连接管理起来
    // 一旦某个连接要关闭,就应该从管理的地方移除掉自己的信息
    ClosedCallback _server_closed_callback;
private:
    /*············································

                五个channel事件的回调函数
    
    ············································*/
    void HandleRead()
    {
        // 1. 接收socket的数据,放到缓冲区
        char buff[65536];
        ssize_t ret = _socket.NonBlockRecv(buff, 65535);
        if (ret < 0) {
            // 这里的等于0表示没有接收到数据,而不是连接断开了,连接断开是返回-1
            // 出错了,调用ShutDownInLoop,不能直接关闭连接
            return ShutDownInLoop();
        }
        // 2. 将数据放入输入缓冲区
        _in_buffer.Write(buff, ret);
        // 3. 调用message_callback进行业务处理
        if (_in_buffer.ReadAbleSize() > 0) {
            return _message_callback(shared_from_this(), &_in_buffer);
        }
        
    }
    void HandleWrite()
    {
        // _out_buffer中保存的数据就是要发送的数据
        ssize_t ret = _socket.NonBlockSend(_out_buffer.ReadPosition(), _out_buffer.ReadAbleSize());
        if (ret < 0) {
            // 发送错误就该关闭连接乐
            if (_in_buffer.ReadAbleSize() > 0) {
                _message_callback(shared_from_this(), &_in_buffer);
            }
            return Release(); // 这时候就是实际的关闭连接
        }
        _out_buffer.MoveReadOffset(ret);  // 将可读指针向后移动
        if (_out_buffer.ReadAbleSize() == 0) {
            _channel.DisableWrite();  // 没有数据该发送乐,关闭写事件监控
            // 处于待关闭状态且没有要发送的数据,则应该关闭连接
            if (_statu == DISCONNECTING) { Release(); }
        }
    }
    void HandleError()
    {
        return HandleClose();
    }
    void HandleClose()
    {
        // 一旦连接挂了,套接字就什么都干不了,因此有数据待处理就处理一下,完毕关闭连接
        if (_in_buffer.ReadAbleSize() > 0) {
            _message_callback(shared_from_this(), &_in_buffer);
        }
        return Release();
    }
    void HandleAnyEvents()
    {
        // 描述符触发任意事件: 
        // 1. 刷新连接的活跃度--延迟定时销毁任务
        // 2. 调用组件使用者的任意事件回调
        if (_enable_inactive_release == true) {
            _loop->TimerRefresh(_conn_id);
        }
        if (_any_events_callback) {
            _any_events_callback(shared_from_this());
        }
    }
    /*············································

      连接获取之后所处的状态下要进行的各种操作设置
      修改连接状态;  启动读事件监控;  调用回调函数
    
    ············································*/
    void EstablishedInLoop()
    {
        // 检测当前状态是否为半连接状态
        assert(_statu == CONNECTING);
        // 将连接状态改成已连接
        _statu = CONNECTED;
        // 因为anyevents会刷新非活跃销毁时间
        // 而一旦启动读事件监控,就可能会立即触发读事件
        // 因此开启读事件监控要放在非活跃销毁之后
        _channel.EnableRead();
        // 调用已连接阶段的回调函数
        if (_connected_callback) { 
            _connected_callback(shared_from_this());
        }
    }
    /*············································

                  实际的关闭接口
    
    ············································*/
    void ReleaseInLoop()
    {
        // 1. 修改连接状态,将其设置为DISCONNECTED
        _statu = DISCONNECTED;
        // 2. 移除连接的事件监控
        _channel.Remove();
        // 3. 关闭描述符
        _socket.Close();
        // 4. 如果当前定时器队列中还有销毁任务,则取消任务
        if (_loop->HashTimer(_conn_id)) { 
            DisableInactiveReleaseInLoop(); 
        }
        // 避免先移除服务器管理的连接信息导致Connection被释放,再去处理会出错,因此先调用用户的回调函数
        // 5. 如果用户设置了关闭阶段的回调函数,则运行
        if (_closed_callback) { _closed_callback(shared_from_this()); }
        // 6. 调用组件内设置的关闭阶段的回调函数,移除服务器内部管理的信息
        if (_server_closed_callback) { 
            _server_closed_callback(shared_from_this()); 
        }
    }
    /*············································

      发送数据,将数据发送到缓冲区,启动写事件监控    
    
    ············································*/
    void SendInLoop(Buffer& data)
    {
        if (_statu == DISCONNECTED) { return; }
        _out_buffer.WriteBuffer(data);
        if (_channel.WriteAble() == false) {
            _channel.EnableWrite();
        }
    }
    /*············································

        提供给组件使用者的关闭接口
        不实际关闭,需判判断是否有数据待处理  
    
    ············································*/
    void ShutDownInLoop()
    {
        // 1. 将状态设置为半关闭连接
        _statu = DISCONNECTING;
        // 2. 检查是否还有没处理的数据
        if (_in_buffer.ReadAbleSize() > 0 && _message_callback) {
            _message_callback(shared_from_this(), &_in_buffer);
        }
        // 3. 检测是否还有未发送的数据
        // 写完后发现处于半连接状态,会自动关闭
        // or写入数据的时候出错关闭
        if (_out_buffer.ReadAbleSize() > 0) {
            if (_channel.WriteAble() == false) {
                _channel.EnableWrite();
            }
        }
        // 没有待发送的数据,直接关闭
        if (_out_buffer.ReadAbleSize() == 0) {
            Release();
        }
    }
    /*············································

        启动非活跃销毁,delay为非活跃销毁时间            
    
    ············································*/
    void EnableInactiveReleaseInLoop(int delay)
    {
        // 将标志为设置为true
        _enable_inactive_release = true;
        // 如果销毁任务已存在,则刷新即可
        if (_loop->HashTimer(_conn_id)) {
            return _loop->TimerRefresh(_conn_id);
        }
        // 如果不存在,则添加定时销毁任务
        _loop->TimerAdd(_conn_id, delay, std::bind(&Connection::Release, this));
    }
    /*············································

                关闭非活跃销毁    
    
    ············································*/
    void DisableInactiveReleaseInLoop()
    {
        // 将标志为设置为false
        _enable_inactive_release = false;
        // 关闭非活跃销毁
        if (_loop->HashTimer(_conn_id)) {
            _loop->TimerCancel(_conn_id);
        }
    }
    /*············································

        切换协议 -- 重置上下文以及阶段性处理函数
    
    ············································*/
    void UpgradeInLoop(const Any& context,
                const ConnectedCallback& conn, const MessageCallback& msg,
                const ClosedCallback& closed, const AnyEventsCallback& event)
    {
        _context = context;
        _connected_callback = conn;
        _message_callback = msg;
        _closed_callback = closed;
        _any_events_callback = event;
    }
public:
    Connection(EventLoop* loop, uint64_t id, int sockfd) 
    :_loop(loop), _conn_id(id), _sockfd(sockfd), _enable_inactive_release(false),
    _statu(CONNECTING), _socket(_sockfd), _channel(_loop, _sockfd)
    {
        _channel.SetReadCallback(std::bind(&Connection::HandleRead, this));
        _channel.SetWriteCallback(std::bind(&Connection::HandleWrite, this));
        _channel.SetErrorCallback(std::bind(&Connection::HandleError, this));
        _channel.SetCloseCallback(std::bind(&Connection::HandleClose, this));
        _channel.SetAnyEventsCallback(std::bind(&Connection::HandleAnyEvents, this));
    }
    ~Connection()
    {
        std::cout << "delete connection! connection_id: " << _conn_id <<  std::endl;
    }
    /*············································

                获取管理的文件描述符
    
    ············································*/
    int GetFd()
    {
        return _sockfd;
    }
    /*············································

                获取连接的ID  
    
    ············································*/
    int GetId()
    {
        return _conn_id;
    }
    /*············································

              判断是否处于CONNECTED状态
    
    ············································*/
    bool IsConnected()
    {
        return (_statu == CONNECTED);
    }
    /*············································

          设置上下文 -- 连接建立完成时进行调用 
    
    ············································*/
    void SetContext(const Any& context)
    {
        _context = context;
    }
    /*············································

              获取上下文, 返回的是指针    
    
    ············································*/
    Any* GetContext()
    {
        return &_context;
    }
    /*············································

             设置提供给用户的四个阶段性处理函数
    
    ············································*/
    void SetConnectedCallback(const ConnectedCallback& cb)
    {
        _connected_callback = cb;
    }
    void SetMessageCallback(const MessageCallback& cb)
    {
        _message_callback = cb;
    }
    void SetClosedCallback(const ClosedCallback& cb)
    {
        _closed_callback = cb;
    }
    void SetAnyEventsCallback(const AnyEventsCallback& cb)
    {
        _any_events_callback = cb;
    }
    /*············································

          设置组件内设置的服务器关闭阶段的回调函数
    
    ············································*/
    void SetSvrClosedCallback(const ClosedCallback& svr_cb)
    {
        _server_closed_callback = svr_cb;
    }
    /*············································

        连接建立就绪后,进行channel回调设置
        启动读监控,调用_connected_callback      

    ············································*/
    void Established()
    {
        _loop->RunInLoop(std::bind(&Connection::EstablishedInLoop, this));
    }
    /*············································

      发送数据,将数据发送到缓冲区,启动写事件监控    
    
    ············································*/
    void Send(const char* data, size_t len)
    {
        // 因为data指向的是临时变量的地址,一个临时的空间
        // 而我们只是将操作压入到任务池中,并没有立马立即被执行
        // 如果将地址传给SendInLoop,执行任务时所指向的空间可能已被销毁
        Buffer buffer_data;
        buffer_data.Write(data, len);
        _loop->RunInLoop(std::bind(&Connection::SendInLoop, this, std::move(buffer_data)));
    }
    /*············································

        提供给组件使用者的关闭接口
        不实际关闭,需判判断是否有数据待处理  
    
    ············································*/
    void ShutDown()
    {
        _loop->RunInLoop(std::bind(&Connection::ShutDownInLoop, this));
    }
    /*············································

                实际的关闭连接操作 
    
    ············································*/
    void Release()
    {
        _loop->QueueInLoop(std::bind(&Connection::ReleaseInLoop, this));
    }
    /*············································

        启动非活跃销毁,delay为非活跃销毁时间            
    
    ············································*/
    void EnableInactiveRelease(int delay)
    {
        _loop->RunInLoop(std::bind(&Connection::EnableInactiveReleaseInLoop, this, delay));
    }
    /*············································

                关闭非活跃销毁    
    
    ············································*/
    void DisableInactiveRelease()
    {
        _loop->RunInLoop(std::bind(&Connection::DisableInactiveReleaseInLoop, this));
    }
    /*············································

        切换协议 -- 重置上下文以及阶段性处理函数
    
    ············································*/
    void Upgrade(const Any& context,
                const ConnectedCallback& conn, const MessageCallback& msg,
                const ClosedCallback& closed, const AnyEventsCallback& event)
    {
        // 切换协议 -- 重置上下文以及阶段性处理函数，而这个接口必须在eventloop线程中立即执行
        // 防备新的事件触发后,处理的时候,切换协议的任务还没被执行,导致数据使用原协议处理了
        _loop->AssertInLoop();
        _loop->RunInLoop(std::bind(&Connection::UpgradeInLoop, this, 
                    context, conn, msg, closed, event));
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Acceptor模块是对Socket模块,Channel模块的⼀个整体封装
    实现了对⼀个监听套接字的整体的管理。

*/
class Acceptor
{
    using AcceptCallback = std::function<void(int)>;
private:
    Socket _socket;    // 用于创建服务器并接收客户端
    EventLoop* _loop;  // 用于监控需要监听的事件
    Channel _channel;  // 用于管理client需要监听的事件

    AcceptCallback _accept_callback;  // 新连接的回调函数
private:
    /*············································

          对创建的服务器套接字进行读事件处理
          即接收新连接上来的客户端      
    
    ············································*/
    void HandleRead()
    {
        int newfd = _socket.Accept();
        if (newfd < 0) {
            return;
        }
        if (_accept_callback) {
            _accept_callback(newfd);
        }
    }
    /*············································

                创建一个SOCKET服务器      
    
    ············································*/ 
    int CreateServer(const uint16_t port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret == true);
        return _socket.GetFd();
    }
public:
    // 不能将客户端fd启动读事件监控放到构造函数中,必须在设置回调函数后再去启动
    // 否则有可能造成启动监控后,立即有事件,但是处理的时候回调函数还没设置
    // 新连接得不到处理,且资源泄漏,因此将客户端可读事件的监控单独分离出来,Listen()
    Acceptor(const uint16_t port, EventLoop* loop)
    : _socket(CreateServer(port)), _loop(loop), 
    _channel(loop, _socket.GetFd())
    {
        _channel.SetReadCallback(std::bind(&Acceptor::HandleRead, this));
    }
    /*············································

                设置Accept阶段的回调函数   
    
    ············································*/
    void SetAcceptCallback(const AcceptCallback& cb)
    {
        _accept_callback = cb;
    }
    /*············································

          对接收上来的套接字客户端开启可读事件监控
    
    ············································*/
    void Listen()
    {
        _channel.EnableRead();
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    TcpServer模块,实现一个服务器启动模块
    内部封装了EventLoop,Acceptor和LoopThreadPool模块

*/
class TcpServer
{
    using PtrConnection = std::shared_ptr<Connection>;
    using ConnectedCallback = std::function<void(const PtrConnection&)>;
    using MessageCallback = std::function<void(const PtrConnection&, Buffer*)>;
    using ClosedCallback = std::function<void(const PtrConnection&)>;
    using AnyEventsCallback = std::function<void(const PtrConnection&)>;
    using Functor = std::function<void()>;
private:
    uint16_t _port;     // 服务器绑定并监听的端口
    uint64_t _conn_id;  // Connection唯一id,从0开始自动增长
    uint32_t _timeout;  // 定时销毁时间
    bool _enable_inactivate_release;  // 是否开启非活跃销毁标志位
    EventLoop _base_loop;   // 主线程EventLoop,即主Reactor
    Acceptor _accept;   // 用于创建服务器并接收新连接
    LoopThreadPool _loops_pool;  // 子线程EventLoop池,即子Reactor池
    std::unordered_map<uint32_t, PtrConnection> _conns;  // 存储所有id与Conn的值键对

    ConnectedCallback _connected_callback;
    MessageCallback _message_callback;
    ClosedCallback _closed_callback;
    AnyEventsCallback _any_events_callback;

private:
    /*············································

              服务器接收新连接的回调函数     
    
    ············································*/
    void NewConnection(const int newfd)
    {
        ++_conn_id;
        PtrConnection new_conn = std::make_shared<Connection>(_loops_pool.NextLoop(), _conn_id, newfd);
        // 设置五个阶段回调函数
        new_conn->SetConnectedCallback(_connected_callback);
        new_conn->SetMessageCallback(_message_callback);
        new_conn->SetClosedCallback(_closed_callback);
        new_conn->SetAnyEventsCallback(_any_events_callback);
        new_conn->SetSvrClosedCallback(std::bind(&TcpServer::RemoveConnection, this, std::placeholders::_1));
        // 检测是否开启非活跃销毁
        if (_enable_inactivate_release) { new_conn->EnableInactiveRelease(_timeout); }
        // 就绪初始化
        new_conn->Established();  
        // 将Connection信息插入到_conns中
        _conns.insert(std::make_pair(_conn_id, new_conn));
    }
    /*············································

                    添加定时任务
    
    ············································*/
    void RunAfterInLoop(const uint32_t delay, const Functor& task)
    {
        ++_conn_id;
        _base_loop.TimerAdd(_conn_id, delay, task);
    }
    /*············································

            从_conns中移除Connection信息 
    
    ············································*/
    void RemoveConnection(const PtrConnection& conn)
    {
        _base_loop.RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop, this, conn));
    }
    void RemoveConnectionInLoop(const PtrConnection& conn)
    {
        uint64_t id = conn->GetId();
        auto it = _conns.find(id);
        if (it != _conns.end()) { _conns.erase(it); }
    }
public:
    TcpServer(const uint16_t port) :_port(port), _conn_id(0), _timeout(0), 
                 _enable_inactivate_release(false), _accept(_port, &_base_loop),  
                 _loops_pool(&_base_loop)          
    {
        // 设置服务器接收新连接的回调函数
        _accept.SetAcceptCallback(std::bind(&TcpServer::NewConnection, this, std::placeholders::_1));
        // 设置服务器开始监听
        _accept.Listen();
    }
    /*············································

           设置LoopThreadPool的线程数量     
    
    ············································*/
    void SetThreadCount(const int count)
    {
        _loops_pool.SetThreadCount(count);
    }
    /*············································

          设置四个阶段的回调函数给Connection 
    
    ············································*/
    void SetConnectedCallback(const ConnectedCallback& cb)
    {
        _connected_callback = cb;
    }
    void SetMessageCallback(const MessageCallback& cb)
    {
        _message_callback = cb;
    }
    void SetClosedCallback(const ClosedCallback& cb)
    {
        _closed_callback = cb;
    }
    void SetAnyEventsCallback(const AnyEventsCallback& cb)
    {
        _any_events_callback = cb;
    }
    /*············································

                开启非活跃连接销毁  
    
    ············································*/
    void EnableInactiveRelease(const int delay)
    {
        _timeout = delay;
        _enable_inactivate_release = true;
    }
    /*············································

                    添加定时任务
    
    ············································*/
    void RunAfter(const int delay, const Functor& task)
    {
        _base_loop.RunInLoop(std::bind(&TcpServer::RunAfterInLoop, this, delay, task));
    }
    /*············································

        创建子Reactor线程池,开启eventloop事件监控
    
    ············································*/
    void Start()
    {
        _loops_pool.Create();
        _base_loop.Start();
    }
};

/*············································

    对Channel中的Remove()和Update()进行实现
    
············································*/
void Channel::Remove()
{
    _loop->RemoveEvent(this);
}
void Channel::Update()
{
    _loop->UpdateEvent(this);
}
/*············································

    对TimerWheel中的TimerAdd(),TimerRefresh()
    和TimerCancel()进行实现
    
············································*/
void TimerWheel::TimerAdd(uint64_t id, uint32_t delay, const TaskFunc& cb)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerAddInLoop, this, id, delay, cb));
}
void TimerWheel::TimerRefresh(uint64_t id)
{   
    _loop->RunInLoop(std::bind(&TimerWheel::TimerRefreshInLoop, this, id));
}
void TimerWheel::TimerCancel(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerCancelInLoop, this, id));
}

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    NetWork模块是为了实现对SIGPIPE信号的处理方式进行忽略
    防止因向不存在的文件描述符内写入信息导致程序终止

*/
class NetWork
{
public:
    NetWork()
    {
        signal(SIGPIPE, SIG_IGN);
    }
};
static NetWork nw;